package com.iot.ic.common.web;

import com.iot.ic.common.mapper.SimpleJsonMapper;
import com.iot.ic.common.utils.DateUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.plaf.metal.MetalIconFactory;
import java.beans.PropertyEditorSupport;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.*;


public abstract class BaseController {

    private final static Logger logger = LoggerFactory
            .getLogger(BaseController.class);

    public String renderString(HttpServletResponse response, Object object) {
        return renderString(response, SimpleJsonMapper.toJsonStr(object), "application/json");
    }


    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(String.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                setValue(text == null ? null : StringEscapeUtils
                        .escapeHtml4(text.trim()));
            }

            @Override
            public String getAsText() {
                Object value = getValue();
                return value != null ? value.toString() : "";
            }
        });
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                setValue(DateUtils.parseDate(text));
            }
        });
    }

    private String renderString(HttpServletResponse response, String value, String type) {
        try {
            response.setContentType(type);
            response.setCharacterEncoding("utf-8");
            response.getWriter().print(value);
            return value;
        } catch (IOException e) {
            return null;
        }
    }


    /**
     * 提示异常
     */
    public Map<String, Object> warnException(Exception e) {
        Map<String, Object> map = new HashMap<>();
        map.put("result", -3);
        map.put("message", "网络异常！");
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        map.put("Exception", sw.toString());
        return map;
    }

    /**
     * 封装数据
     */
    @SuppressWarnings("rawtypes")
    public Map<String, Object> packData(Object obj) {
        Map<String, Object> map = new HashMap<>();
        map.put("result", 0);
        map.put("data", obj);
        if (obj instanceof List) {
            map.put("count", ((List) obj).size());
        }
        map.put("message", "查询成功！");
        return map;
    }

    public Map<String, Object> packSaveInfo(Object obj) {
        if (obj == null) {
            return packInfo(false, "保存");
        } else {
            Map<String, Object> map = packInfo(true, "保存");
            map.put("data", obj);
            return map;
        }
    }

    public Map<String, Object> packDelInfo(boolean success) {
        return packInfo(success, "删除");
    }

    public Map<String, Object> packInfo(boolean success, String info) {
        return packInfo(success, info, null);
    }

    public Map<String, Object> packInfo(boolean success, String info, String paramName) {
        Map<String, Object> map = new HashMap<>();
        if (success) {
            map.put("result", 0);
            map.put("message", info + "成功！");
        } else {
            map.put("result", -1);
            map.put("message", info + "失败！");
        }
        if (paramName != null) {
            map.put("paramName", paramName);
        }
        return map;
    }


    /**
     * 采用spring的保存文件的方法
     *
     * @return 文件路径
     */
    public List<String> springUpload(HttpServletRequest request, String userName, String paramName) throws IOException {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            List<String> list = new ArrayList<String>();
            List<MultipartFile> files = multiRequest.getFiles(paramName);
            for (int i = 0; i < files.size(); i++) {
                MultipartFile file =files.get(i);
                if (file != null && !file.isEmpty()) {
                    String path = request.getSession().getServletContext().getRealPath("").replace("iotic", "uploadFile")
                            + "/" + paramName + "/";
                    String fileName = userName + "_" + DateUtils.formatNow(12) + "_" + file.getOriginalFilename();
                    list.add("uploadFile/" + paramName + "/" + fileName);
                    file.transferTo(new File(path + fileName));
                }
            }
            return list;
        } else {
            return null;
        }

    }
}
